<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class IPServiceProvider extends ServiceProvider
{

    public static $api_url = 'http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json';
    public static $api_url_taobao = 'http://ip.taobao.com/service/getIpInfo.php';
    public static function getIP(){

        if (getenv("HTTP_CLIENT_IP"))
            $ip = getenv("HTTP_CLIENT_IP");
        else if(getenv("HTTP_X_FORWARDED_FOR"))
            $ip = getenv("HTTP_X_FORWARDED_FOR");
        else if(getenv("REMOTE_ADDR"))
            $ip = getenv("REMOTE_ADDR");
        else $ip = "Unknow";
        return $ip;

    }

    public static function getAddressByIP( $ip ){

        $address = array();
        if( $ip != 'Unknow' ){
            $res = MyCurlServiceProvider::send( self::$api_url . '&ip=' . $ip );
            $json = json_decode( $res, true );
            if( is_array( $json )){
                $address = array(
                    'ip'=>$ip,
                    'country'=>$json['country'],
                    'province'=>$json['province'],
                    'city'=>$json['city']
                );
            }
        }

        return $address;

    }

    /**
     * 淘宝接口
     * @param $ip
     * @return array
     */
    public static function getAddressByIPFromTaobao( $ip ){

        $address = array();
        if( $ip != 'Unknow' ){
            $res = MyCurlServiceProvider::send( self::$api_url_taobao . '?ip=' . $ip );
            $json = json_decode( $res, true );
            if( $json['code'] == 0 ){
                $address = array(
                    'ip'=>$ip,
                    'country'=>$json['data']['country'],
                    'province'=>$json['data']['region'],
                    'city'=>$json['data']['city'],
                    'isp'=>$json['data']['isp']
                );
            }
        }

        return $address;

    }

    public static function address(){

        $ip = self::getIP();
//        $address = self::getAddressByIP( $ip );
        $address = self::getAddressByIPFromTaobao( $ip );
        return $address;
    }
}
